import axios from "axios";
import store from "../store";
import Router from "vue-router"
import { Loading, Message } from "element-ui";
const loading = {
  loaddingInstance: null, //Loading实例
  //打开加载
  open: function() {
    if (this.loaddingInstance === null) {
      //如果实例为空，则创建
      this.loaddingInstance = Loading.service({
        target: ".app-body",
        text: "拼命加载中呢小可爱~",
        background: "rgba(0,0,0,0.2)"
      });
    }
  },
  //关闭加载
  close: function() {
    if (this.loaddingInstance !== null) {
      this.loaddingInstance.close();
    }
    this.loaddingInstance = null;
  }
};

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000,


});

request.interceptors.request.use(
  config => {
    config.headers.common={
      'Authorization':'Bearer '+store.state.user.token
    }
    //请求拦截
    loading.open();
    return config;
  },
  error => {
    //出现异常
    loading.close();
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  response => {

    loading.close();
    //响应拦截
    const respData = response.data;
    //后台正常响应的状态，如果不是2000，说明后台处理有问题
    /*if (respData.code !== 2000) {
      Message({
        message: respData.message,
        type: "warning",
        duration: 5 * 1000
      });
    }*/
    if(respData.code !==2000){
     
      Message({
        message:respData.message,
        type:'warning',
        duration:2000,
      })
     
    }
    
     
    return response;
  },
  error => {
    loading.close();
    /*Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });*/
    if(error.response.status){
        switch(error.response.status){
          case 404:
              Message({
                message:"您请求的页面好像已经丢失了哦",
                duration:2000,
              })
             
            
              break;
          case 403:
            Message({
              message:error.response.data,
              duration:2000,
            })
            store.commit("SET_TOKEN", "");
            store.commit("SET_ROLE", "");
            store.commit("SET_USER", "");
     
            Router.replace({
                path:'/login',
                query:{
                  redirect: this.$router.currentRoute.fullPath
                }
              })
        
            break;
      
          default:
              Message({
                message:error.response.message,
                duration:2000,
              })
              Router.push("/error")
        }

    }
    
    return Promise.reject(error);
  }
);

export default request;
